package com.botann.projects.service;

import com.botann.projects.base.BaseService;
import com.botann.projects.model.Role;
import com.botann.projects.base.BaseService;
import com.botann.projects.constants.Code;
import com.botann.projects.constants.Constant;
import com.botann.projects.model.AdminUser;
import com.botann.projects.model.Role;
import com.sun.istack.internal.NotNull;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Charging
 * RoleService
 * Created by 刘山国 on 2017/11/29.
 * Copyright (c) 2017 刘山国. All rights reserved
 */
@Service
public class RoleService extends BaseService implements RoleServiceIntf{
    @Override
    public Class loggerClass() {
        return RoleService.class;
    }

    @Override
    public Role loadRoleWithName(String roleName) {
        return sessionGet(Role.class,conditions("roleName=","del="), roleName.trim(),false);
    }

    @Override
    public Role addRole(String roleJson) {
        Role role = jsonToModel(roleJson,Role.class);
        role.setName(role.getName().trim());
        if (loadRoleWithName(role.getName())!=null) throw sgWrongParamRuntimeException("角色名称重复!");
        role.setAuthority(Constant.ROLE_SUPER_ADMIN +","+ Constant.ROLE_ADMIN);
        sessionSave(role);
        return role;
    }

    @Override
    public void updateRole(String roleJson) {
        Role role = jsonToModel(roleJson,Role.class);
        if (loadRoleWithName(role.getName())!=null) throw sgWrongParamRuntimeException("角色名称重复!");
        sessionUpdate(role);            //就直接调用update(),也不管是删除呢，还是添加，还是更新内容？ ---这里应该就单指更新内容
    }

    @Override
    public void deleteRoles(@NotNull List<Integer> roleIds) {
        roleIds.forEach((Integer roleId) -> {
            List<AdminUser> adminUsers = sessionQuery(AdminUser.class,"roleId=",roleId);
            if (adminUsers.size()>0) {
                Role role = sessionGetNN(Role.class,roleId);
                throw sgRuntimeException(Code.ERROR,"还有属于角色"+role.getName()+"的管理员,不可删除!");
            }
            sessionDelete(Role.class,roleId);
        });
    }

    @Override
    public List<Role> loadRoles() {
        return sessionQuery(Role.class,conditions(delCondition),false);
    }
}
